package com.example.service.impl;

import ch.qos.logback.classic.Logger;
import com.example.entity.*;
import com.example.entity.authority.SystemUser;
import com.example.ext.entity.ExtElevator;
import com.example.ext.entity.ExtRepairInfo;
import com.example.mapp.*;
import com.example.service.RepairInfoService;
import com.example.util.PromotionUtil;
import com.example.util.ResultUtil;
import com.example.util.SystemPointUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by youkun on 2017/10/24.
 */
@Service
public class RepairInfoServiceImpl implements RepairInfoService{

    private final static Logger logger = (Logger) LoggerFactory.getLogger(RepairInfoServiceImpl.class);

    @Autowired
    private RepairInfoMapp repairInfoMapp;

    @Autowired
    private MessageNoticeMapp messageNoticeMapp;

    @Autowired
    private SysUserMapp sysUserMapp;

    @Autowired
    private ElevatorMapp elevatorMapp;

    @Autowired
    private PromotionMapp promotionMapp;

    @Autowired
    AfterDoMapp afterDoMapp;

    @Autowired
    PointFlowMapp pointFlowMapp;


    @Override
    public Map<String, Object> queryByElevatorList(ExtRepairInfo extRepairInfo) {
        List<ExtRepairInfo> list =null;
        Map<String,Object> map = new HashMap<String,Object>();
        try {
//            Page<ExtRepairInfo> page = PageHelper.startPage(extRepairInfo.getCurrentPage(), extRepairInfo.getPageSize());
            list = repairInfoMapp.queryByElevatorList(extRepairInfo);
            int total = repairInfoMapp.countByElevatorList(extRepairInfo);
            map.put("list",list);
            map.put("total",total);

        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("查询成功",map);
    }

    @Override
    public Map<String, Object> queryByIdElevator(String id) {
        ExtRepairInfo repairInfo = null;
        try{
            repairInfo = repairInfoMapp.queryById(id);
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("查询成功",repairInfo);
    }

    @Override
    @Transactional
    public Map<String, Object> add(RepairInfo repairInfo) {
        try{
            repairInfoMapp.add(repairInfo);
            Map map = new HashMap();
            map.put("elevatorNum",repairInfo.getElevatorNum());
            map.put("resolveDate",repairInfo.getResolveDate());
            ExtRepairInfo extRepairInfo = repairInfoMapp.findRepairInfoId(map);
            ExtElevator extElevator = elevatorMapp.queryById(repairInfo.getElevatorId()+"");

            String content = "设备代码为："
                    + extElevator.getElevatorNum() + "的电梯，维保已经维修完成，请您及时去确认是否已经修复。";
            String noticeTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

            MessageNotice msg = new MessageNotice();
            msg.setTitle("电梯维修结果确认通知");
            msg.setContent(content);
            msg.setReceiveUserId(String.valueOf(extElevator.getSafeUserId()));
            msg.setIsRead("0");
            msg.setNoticeTime(noticeTime);
            msg.setReceivePartyId(String.valueOf(extElevator.getUsedPartyId()));
            msg.setElevatoriType("8");//消息类型
            msg.setElevatoriMonId(Long.toString(extRepairInfo.getId()));//维修记录id
            messageNoticeMapp.add(msg);

            try{
                AfterDo afterDo = new AfterDo();
                afterDo.setEventType("3");
                afterDo.setStatus("1");
                AfterDo afterDo1 = afterDoMapp.findByType(afterDo);
                return ResultUtil.returnSuccess("提交成功", afterDo1);
            }catch (Exception e){
                logger.error("查询维修场景失败",e);
            }
        }catch (Exception e){
        	TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error(e.getMessage(),e);
            return ResultUtil.returnError("添加失败"+e.getMessage(),null);
        }finally {
            if (repairInfo != null) {
                // 获取一份维修记录缓存
                PointDefendInfoCache infoCache = new PointDefendInfoCache();
                PointDefend defend = infoCache.getKeyByValue("maintenance_records");

                // 获取当前用户，计算积分
                Long userId = repairInfo.getRepairUserId();
                Map<String, Object> maps = pointFlowMapp.findUserInfoByUserId(userId);
                long mark = (long) maps.get("mark");
                int round = (int) (mark + defend.getMark());

                // 更新用户信息总积分
                String userIds = maps.get("userId").toString();
                int i1 = pointFlowMapp.updateMark(round, userIds);

                String userName = maps.get("userName").toString();
                String partyName = maps.get("partyName").toString();
                SystemPointUtil.insertFlow(pointFlowMapp, i1, defend, round, userName, partyName, "提交一份维修记录");


                // 维修加使用单位的积分
                PointDefend defendUnit = infoCache.getKeyByValue("inspection_record_units");
                // 获取单位Id
                Long partyId = repairInfo.getRepairPartyId();
                Map<String, Object> mapUnit = pointFlowMapp.findUserInfo(partyId);

                long markUnit = (long) mapUnit.get("mark");
                int roundUnit = (int) (markUnit + defendUnit.getMark());

                // 更新用户信息总积分
                String userIdUnit = mapUnit.get("userId").toString();
                int i2 = pointFlowMapp.updateMark(roundUnit, userIdUnit);

                String name = mapUnit.get("userName").toString();
                String pname = mapUnit.get("partyName").toString();
                SystemPointUtil.insertFlow(pointFlowMapp, i2, defendUnit, roundUnit, name, pname, "提交一份巡检记录加单位的积分");
            }
        }
        return ResultUtil.returnSuccess("添加成功",null);
    }

    @Override
    @Transactional
    public Map<String, Object> update(RepairInfo repairInfo) {
        try{
            repairInfoMapp.update(repairInfo);
            //发送通知，把维修结果告诉维修确认人
            SystemUser user = sysUserMapp.findById(repairInfo.getRepairUserId()+"");
            ExtElevator extElevator = elevatorMapp.queryById(repairInfo.getElevatorId() + "");
            String title = "";
            String content = "";
            if("1".equals(repairInfo.getIsRepaired())){
                title = "电梯已修复通知";
                content= "设备代码为："+repairInfo.getElevatorNum()+" 的电梯已修复，感谢您的辛勤工作。";
            }else{
                title = "电梯未修复通知";
                content= user.getUserName()+"检查电梯修复情况后确定，设备代码为："+repairInfo.getElevatorNum()+" 的电梯未修复，请悉知。";
            }
            String noticeTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            MessageNotice msg2 = new MessageNotice();
            msg2.setTitle(title);
            msg2.setContent(content);
            msg2.setReceiveUserId(String.valueOf(repairInfo.getRepairUserId()));
            msg2.setIsRead("0");
            msg2.setNoticeTime(noticeTime);
            msg2.setReceivePartyId(String.valueOf(repairInfo.getRepairPartyId()));
            messageNoticeMapp.add(msg2);
        }catch (Exception e){
        	TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error(e.getMessage(),e);
            return ResultUtil.returnError("添加失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("添加成功",null);
    }

    @Override
    public Map<String, Object> queryUsedRepairList(Map<String, Object> inMap) {
        List<ExtRepairInfo> list =null;
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            Page<ExtRepairInfo> page = PageHelper.startPage(1, 50);
            list = repairInfoMapp.queryUsedRepairList(inMap);
            map.put("list",list);
            map.put("total",page.getTotal());

        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("查询成功",map);
    }

    @Override
    public Map<String, Object> queryRepairInfoById(Map<String, Object> inMap) {
        ExtRepairInfo repairInfo = null;
        try {
            repairInfo = repairInfoMapp.queryRepairInfoById(inMap);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("查询成功",repairInfo);
    }
}
